<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">🍃 智慧果园实时监测中心</text>
      <text v-if="!connected" class="status connecting">🔌 正在连接中...</text>
      <text v-else class="status ok">✅ 已连接服务器</text>
    </view>

    <!-- 实时数据卡片 -->
    <view class="card-box">
      <view class="card">
        <text class="card-title">🌡 温度</text>
        <text class="card-value">{{ data.temp.toFixed(2) }} ℃</text>
      </view>

      <view class="card">
        <text class="card-title">🌱 土壤湿度</text>
        <text class="card-value">{{ data.soilM }}</text>
      </view>

      <view class="card">
        <text class="card-title">💧 雨滴强度</text>
        <text class="card-value">{{ data.raindrops }}</text>
      </view>
    </view>

    <!-- 果树类型选择 -->
    <view class="type-section">
      <text class="section-title">🍎 果树类型</text>
      <scroll-view scroll-x class="type-scroll">
        <view
          v-for="(item, index) in treeTypes"
          :key="index"
          class="type-item"
          :class="{ active: item === selectedType }"
          @click="selectType(item)"
        >
          {{ item }}
        </view>
      </scroll-view>
    </view>

    <!-- 历史警报展示 -->
    <view class="alert-section">
      <text class="section-title">⚠️ 历史警报信息</text>

      <!-- 无数据提示 -->
      <view v-if="alertList.length === 0" class="empty">
        暂无警报记录
      </view>

      <!-- 警报卡片 -->
      <scroll-view
        scroll-y
        class="alert-list"
        @scrolltolower="loadMore"
      >
        <view
          v-for="(alert, index) in alertList"
          :key="index"
          :class="['alert-item', getAlertLevel(alert.message)]"
        >
          <view class="alert-header">
            <text class="alert-time">{{ alert.time }}</text>
            <text class="alert-level">{{ getAlertLabel(alert.message) }}</text>
          </view>
          <text class="alert-message">{{ alert.message }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { connectWebSocket, closeWebSocket, getWebSocket } from '@/utils/websocket.js'
import { onShow, onHide } from '@dcloudio/uni-app'

// ==================== 实时监测数据 ====================
const connected = ref(false)
const data = ref({ temp: 0, soilM: 0, raindrops: 0 })
let ws = null

const initWebSocket = () => {
  if (getWebSocket()) closeWebSocket();
	  
  ws = connectWebSocket('ws://localhost:8080/ws/tree', (msg) => {
    connected.value = true
    try {
      const jsonData = JSON.parse(msg)
      data.value = jsonData
    } catch (e) {
    }
  });

  ws.onOpen(() => {
    connected.value = true;
  });

  ws.onClose(() => {
    connected.value = false;
  });
}

// tabBar 页面显示/隐藏事件
onShow(() => initWebSocket())
onHide(() => closeWebSocket())

// ==================== 果树类型与警报展示 ====================
const treeTypes = ref([])
const selectedType = ref('')
const alertList = ref([])
const page = ref(1)
const size = ref(10)
const loading = ref(false)
const finished = ref(false)

const token =`Bearer ${uni.getStorageSync('token')}` // 示例用，实际请替换为登录后token

// 获取果树类型
const getTreeTypes = async () => {
  try {
    const res = await uni.request({
      url: 'http://localhost:8080/device/show/showType',
      method: 'POST',
      header: { Authorization: token }
    })
    if (res.statusCode === 200) {
      treeTypes.value = res.data
      if (res.data.length > 0) {
        selectType(res.data[0])
      }
    }
  } catch (e) {
    console.error('获取果树类型失败:', e)
  }
}

// 解析报警字符串 -> { time, message }
const parseAlert = (str) => {
  if (!str || typeof str !== 'string') {
    return { time: '', message: '' }
  }

  // 格式 "2025-10-28 17:15:47 降雨量超出阈值；"
  // 找到第三个空格位置：日期 + 时间 + 内容
  const parts = str.trim().split(' ')
  if (parts.length >= 3) {
    const time = `${parts[0]} ${parts[1]}`
    const message = parts.slice(2).join(' ').replace(/；$/, '')
    return { time, message }
  }

  return { time: '', message: str.trim().replace(/；$/, '') }
}


// 获取警报历史
const loadAlerts = async (reset = false) => {
  if (loading.value ) return
  loading.value = true
  if (reset) {
	finished.value = false
    page.value = 1
    alertList.value = []
  }

  try {
    // 构造 URL，符合后端参数要求
    let url = `http://localhost:8080/device/show/treeAlertHistory?type=${selectedType.value}&page=${page.value}`
    if (size.value) url += `&size=${size.value}`

    const res = await uni.request({
      url,
      method: 'POST',
	  header: { Authorization: token } // 如果后端需要授权，必须加上
    })

    if (res.statusCode === 200) {
      let list = res.data

      // 🚨 如果后端返回的是字符串（如 '["xxx","yyy"]'），需要手动解析
      if (typeof list === 'string') {
        try {
          list = JSON.parse(list)
        } catch {
          console.error('JSON解析失败:', list)
          list = []
        }
      }

      // 转换为对象数组
      const parsed = list.map(parseAlert)

      if (parsed.length === 0) {
        finished.value = true
      } else {
        alertList.value.push(...parsed)
        page.value++
      }
    }
  } catch (e) {
    console.error('获取历史警报失败:', e)
  } finally {
    loading.value = false
  }
}

// 切换果树类型
const selectType = (type) => {

  selectedType.value = type
  loadAlerts(true)
}

// 滚动触底加载更多
const loadMore = () => {
  if (!finished.value) loadAlerts()
}

// 根据内容判断报警等级
const getAlertLevel = (message) => {
  if (!message) return 'normal'
  if (message.includes('严重') || message.includes('超出') || message.includes('过高') || message.includes('低于')) return 'danger'
  if (message.includes('偏高') || message.includes('偏低')) return 'warning'
  return 'normal'
}

// 报警标签显示
const getAlertLabel = (message) => {
  if (message.includes('严重')) return '严重'
  if (message.includes('超出') || message.includes('低于')) return '警告'
  return '提示'
}

onMounted(() => {
  getTreeTypes()
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f7f7f7;
  min-height: 100vh;
  padding: 40rpx;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
}

.status {
  display: block;
  margin-top: 10rpx;
  font-size: 26rpx;
}

.status.connecting {
  color: #ff9800;
}

.status.ok {
  color: #22bb33;
}

.card-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-bottom: 60rpx;
}

.card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card-title {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.card-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #2c7ef8;
}

/* 果树类型选择 */
.type-section {
  width: 100%;
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.type-scroll {
  display: flex;
  flex-direction: row;
  gap: 20rpx;
}

.type-item {
  background: #fff;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  color: #555;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.type-item.active {
  background: #ff5500;
  color: #fff;
}

/* 历史警报 */
.alert-section {
  width: 100%;
}

.alert-list {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  max-height: 600rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.08);
}

.alert-item {
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  margin-bottom: 20rpx;
  color: #fff;
}

.alert-item.normal {
  background-color: #4caf50;
}

.alert-item.warning {
  background-color: #ff9800;
}

.alert-item.danger {
  background-color: #e74c3c;
}

.alert-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.alert-time {
  font-size: 26rpx;
}

.alert-level {
  font-size: 26rpx;
  font-weight: bold;
}

.alert-message {
  font-size: 30rpx;
}

.empty {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 40rpx 0;
}
</style>
